// VideoDownloaderHelper - Helper Tool for macOS Sandbox Bypass
import Foundation
import Darwin

// 信号处理用于优雅关闭
var globalHelper: VideoDownloaderHelper?

func signalHandler(signal: Int32) {
    print("\nReceived signal \(signal), shutting down gracefully...")
    exit(0)
}

// 命令行参数处理
func main() {
    // 设置信号处理
    signal(SIGINT, signalHandler)
    signal(SIGTERM, signalHandler)
    
    let helper = VideoDownloaderHelper()
    globalHelper = helper
    
    if CommandLine.arguments.count > 1 {
        let command = CommandLine.arguments[1]
        
        switch command {
        case "start":
            print("🚀 Starting VDH server in background...")
            if isServerRunning() {
                print("⚠️ Server is already running")
                exit(0)
            }
            startServerInBackground()
            
        case "stop":
            print("🛑 Stopping VDH server...")
            if !isServerRunning() {
                print("⚠️ Server is not running")
                exit(0)
            }
            stopServer()
            
        case "server":
            print("Starting Helper Tool Socket Server...")
            helper.startServer()
            
        case "download", "-d":
            if CommandLine.arguments.count > 2 {
                let url = CommandLine.arguments[2]
                print("🎬 Starting direct download for: \(url)")
                
                // 为直接下载创建数据库任务
                let taskId = helper.dbManager.addTask(url: url)
                if let taskId = taskId {
                    print("📝 Created task with ID: \(taskId)")
                    let success = helper.downloadVideo(url: url, downloadId: taskId)
                    if success {
                        print("✅ Direct download completed successfully")
                    } else {
                        print("❌ Direct download failed")
                    }
                } else {
                    print("❌ Failed to create database task")
                    let success = helper.downloadVideo(url: url)
                    if success {
                        print("✅ Direct download completed (without database tracking)")
                    } else {
                        print("❌ Direct download failed")
                    }
                }
            } else {
                print("Usage: vdh download <URL> or vdh -d <URL>")
            }

        case "input", "-i", "send":
            if CommandLine.arguments.count > 2 {
                let url = CommandLine.arguments[2]
                print("Sending download request via Unix socket...")
                if sendToSocket(url: url) {
                    print("Request sent successfully")
                } else {
                    print("Failed to send request")
                }
            } else {
                print("Usage: vdh input <URL> or vdh -i <URL>")
            }
            
        case "status":
            print("📊 Checking VDH server status...")
            checkServerStatus()
            
        case "task":
            if CommandLine.arguments.count > 2 {
                let taskId = CommandLine.arguments[2]
                print("Getting task details for ID \(taskId)...")
                if sendTaskQuery(taskId: taskId) {
                    print("Task query completed")
                } else {
                    print("Failed to get task details - make sure server is running")
                }
            } else {
                print("Usage: vdh task <ID>")
            }
            
        case "list", "ls":
            print("Getting recent tasks list...")
            if sendListQuery() {
                print("List query completed")
            } else {
                print("Failed to get task list - make sure server is running")
            }
            
        case "cleanup":
            print("Cleaning up old completed tasks...")
            let helper = VideoDownloaderHelper()
            let deletedCount = helper.dbManager.cleanupOldTasks()
            print("Cleanup completed: \(deletedCount) old tasks removed")
            
        case "stats":
            print("Getting task statistics...")
            let helper = VideoDownloaderHelper()
            let stats = helper.dbManager.getTaskStats()
            print("📊 Task Statistics:")
            for status in TaskStatus.allCases {
                let count = stats[status] ?? 0
                let emoji = helper.getStatusEmoji(status)
                print("  \(emoji) \(status.rawValue.capitalized): \(count)")
            }
            let total = stats.values.reduce(0, +)
            print("  📋 Total: \(total)")
            
        case "config":
            if CommandLine.arguments.count > 2 {
                let subCommand = CommandLine.arguments[2]
                let configManager = ConfigManager()
                
                switch subCommand {
                case "show":
                    configManager.printConfig()
                    
                case "edit":
                    print("📝 Opening config file for editing...")
                    let configPath = NSHomeDirectory() + "/.vdh/config.yaml"
                    print("Config file location: \(configPath)")
                    print("💡 Edit the file and run 'vdh config reload' to apply changes")
                    
                    // 尝试用默认编辑器打开
                    let task = Process()
                    task.launchPath = "/usr/bin/open"
                    task.arguments = ["-t", configPath]  // -t 表示用文本编辑器打开
                    try? task.run()
                    
                case "reload":
                    print("🔄 Reloading configuration...")
                    configManager.reloadConfig()
                    print("✅ Configuration reloaded")
                    configManager.printConfig()
                    
                case "reset":
                    print("⚠️ This will reset all settings to default values")
                    print("Are you sure? (y/N): ", terminator: "")
                    if let input = readLine(), input.lowercased() == "y" {
                        let defaultConfig = ConfigManager.Config.defaultConfig()
                        configManager.updateConfig(defaultConfig)
                        print("✅ Configuration reset to defaults")
                        configManager.printConfig()
                    } else {
                        print("❌ Reset cancelled")
                    }
                    
                default:
                    print("Available config commands:")
                    print("  vdh config show    - Show current configuration")
                    print("  vdh config edit    - Open config file for editing")
                    print("  vdh config reload  - Reload configuration from file")
                    print("  vdh config reset   - Reset to default configuration")
                }
            } else {
                // 默认显示配置
                let configManager = ConfigManager()
                configManager.printConfig()
            }
            
        case "test":
            print("Testing Unix socket communication...")
            let testUrl = "https://www.youtube.com/watch?v=dQw4w9WgXcQ"
            if sendToSocket(url: testUrl) {
                print("Socket test completed successfully")
            } else {
                print("Socket test failed")
            }
            
        case "--help", "-h", "help":
            printHelp()
            
        case "--version", "-v", "version":
            print("VDH (Video Downloader Helper) v2.0.0")
            print("Unix Socket-based video downloader with SQLite database and queue management")
            print("Features: Task persistence, status tracking, queue recovery")
            
        default:
            print("Unknown command: \(command)")
            print("Use 'vdh --help' for usage information")
        }
    } else {
        printHelp()
    }
}

main()
